﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using iOak.Data.Users;
using iOak.Domain.Users;
using System.Security.Cryptography;
using iOak.Business.Security;

namespace iOak.Business.Users
{
    public partial class UserService
    {
        private readonly UserRepository _repository = null;
        private readonly EncryptionService _encryptionService = null;

        public UserService()
        {
            _repository = new UserRepository("master");
            _encryptionService = new EncryptionService();
        }
        public virtual bool ValidateUser(string username, string password)
        {
            var user = _repository.Retrieve(username);

            if (user == null || !user.Active) return false;

            string passwordHash =_encryptionService.CreatePasswordHash(password, user.SaltKey);
            bool result = user.PasswordHash.Equals(passwordHash);

            return result;
        }



        public virtual User GetUserByName(string username)
        {
            return _repository.Retrieve(username);
        }

        public virtual User GetUserById(Guid id)
        {
            return _repository.Retrieve(id);
        }

        public List<User> GetListByCompanyId(Guid companyId)
        {
            return _repository.GetListByCompanyId(companyId);
        }

        public void Create(User user)
        {
            string saltkey = _encryptionService.CreateSaltKey(5);
            user.SaltKey = saltkey;
            user.PasswordHash = _encryptionService.CreatePasswordHash(user.PasswordHash, saltkey);
            _repository.Create(user);
        }

        public void RegisterUser(User user)
        {
            string saltkey = _encryptionService.CreateSaltKey(5);
            user.SaltKey = saltkey;
            user.PasswordHash = _encryptionService.CreatePasswordHash(user.PasswordHash, saltkey);
            _repository.Create(user);
        }

        public void Update(User user)
        {
            _repository.Update(user);
        }

        public void Delete(Guid userId)
        {
            _repository.Delete(userId);
        }
    }
}
